#region Usings
using UnityEngine;
#endregion

/// <summary>
/// Animate sprite (spritesheet)
/// </summary>
public class SpriteAnimator : MonoBehaviour
{
    /// <summary>
    /// Animate a sprite
    /// </summary>
    /// <param name="columnSize">number of horizontal frames (of animation)</param>
    /// <param name="rowSize">number of vertical frames (of animation)</param>
    /// <param name="colFrameStart">where frame starts (remember 0 is first number in counting)</param>
    /// <param name="rowFrameStart">where frame starts (remember 0 is first number in counting)</param>
    /// <param name="totalFrames">number of frames in the animation (count regular)</param>
    /// <param name="framesPerSecond">how fast do you want it to play through (Standard: 12 - 30 fps)</param>
    public void AnimateSprite(int columnSize, int rowSize, int colFrameStart, int rowFrameStart, int totalFrames, int framesPerSecond)
    {
        //Get index of the frame
        int index = (int)(Time.time * framesPerSecond);
        index = index % totalFrames;

        //Set size and  width of a frame
        Vector2 size = new Vector2(1.0f / columnSize, 1.0f / rowSize);

        //Get uv-coords on texture
        float u = index % columnSize;
        float v = (float)(index / columnSize);

        //Calculate offset
        Vector2 offset = new Vector2((u + colFrameStart) * size.x, (1.0f - size.y) - (v + rowFrameStart) * size.y);

        //Set offset and scale
        renderer.material.mainTextureOffset = offset;
        renderer.material.mainTextureScale = size;
    }
}
